<!--
 * @Author: WangShuai 1830773767@qq.com
 * @Date: 2025-09-26 10:25:48
 * @LastEditors: WangShuai 1830773767@qq.com
 * @LastEditTime: 2025-09-26 14:27:35
 * @FilePath: \app\src\components\takephoto.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
	<div class="mainContainer">
		<div class="up" v-if="!imageUrl && !qrRander">
			<video
				ref="video"
				class="video-preview"
				autoplay
				playsinline
				:width="videoWidth"
				:height="videoHeight"
			></video>
		</div>
		<div class="up" v-if="qrRander">
			<div id="qr-reader"></div>
		</div>
		<!-- 预览 -->
		<div class="up" v-if="imageUrl">
			<img :src="imageUrl" alt="拍摄的照片" class="captured-image" />
		</div>
		<div class="down">
			<el-button type="primary" size="small" @click="codeScanner"
				>扫码</el-button
			>
			<el-button type="primary" size="small" @click="starTakePhoto"
				>开始</el-button
			>
			<el-button type="primary" size="small" @click="takePhoto"
				>拍照</el-button
			>
			<el-button :plain="true" size="small" @click="resetTakePhoto"
				>重拍</el-button
			>
			<el-button :plain="true" size="small" @click="confirmFn"
				>确定</el-button
			>
		</div>
	</div>
</template>

<script>
//扫描二维码依赖库
import { Html5QrcodeScanner } from 'html5-qrcode'
export default {
	name: 'takePhoto',
	components: {},
	data() {
		return {
			// 视频相关配置
			videoWidth: 350,
			videoHeight: 200,
			stream: null,
			// 图片相关
			imageUrl: '', // 存储base64格式图片
			qrRander: true, //扫码区域
			isProcessing: false,
			// 错误信息
			errorMessage: '',
		}
	},
	mounted() {},
	beforeDestroy() {
		this.stopCamera()
	},
	methods: {
		//初始化相机
		async initCamera() {
			try {
				// 获取视频元素
				const video = this.$refs.video

				// 请求相机权限并获取媒体流
				this.stream = await navigator.mediaDevices.getUserMedia({
					video: {
						width: this.videoWidth,
						height: this.videoHeight,
						facingMode: 'environment', // 使用后置摄像头，'user'为前置
					},
				})

				// 将媒体流分配给视频元素
				video.srcObject = this.stream

				// 清除错误信息
				this.errorMessage = ''
			} catch (error) {
				console.error('相机初始化失败:', error)
				this.errorMessage = '无法访问相机，请确保已授予相机权限'
			}
		},
		//开始
		starTakePhoto() {
			this.qrRander = false
			this.$nextTick(() => {
				this.initCamera()
			})
		},
		// 拍照
		takePhoto() {
			if (this.isProcessing) return
			this.isProcessing = true
			try {
				// 创建canvas元素用于捕获视频帧
				const canvas = document.createElement('canvas')
				canvas.width = this.videoWidth
				canvas.height = this.videoHeight

				// 获取视频元素
				const video = this.$refs.video

				// 在canvas上绘制当前视频帧
				const context = canvas.getContext('2d')
				context.drawImage(video, 0, 0, canvas.width, canvas.height)

				// 将canvas内容转换为base64格式的图片
				this.imageUrl = canvas.toDataURL('image/jpeg', 0.9)

				// 停止相机流
				this.stopCamera()
			} catch (error) {
				console.error('拍照失败:', error)
				this.errorMessage = '拍照失败，请重试'
			} finally {
				this.isProcessing = false
			}
		},
		//停止拍照
		stopCamera() {
			if (this.stream) {
				this.stream.getTracks().forEach((track) => {
					track.stop()
				})
				this.stream = null
			}
		},
		//重拍
		resetTakePhoto() {
			this.imageUrl = ''
			this.stopCamera()
			this.initCamera()
			this.takePhoto()
		},
		//扫码
		codeScanner() {
			const config = { fps: 10, qrbox: 250 }
			const html5QrCodeScanner = new Html5QrcodeScanner(
				'qr-reader',
				// { fps: 10, qrbox: 250 },
				config,
				/* verbose= */ false
			)
			html5QrCodeScanner.render(
				(decodedText, decodedResult) => {
					// 处理扫码结果
					console.log(`QR Code decoded`, decodedText, decodedResult)
					// 这里可以将解码的文本（如证件号码）用于后续处理
					html5QrCodeScanner.clear() // 停止扫描并释放摄像头
				},
				(errorMessage) => {
					// 处理错误情况
					console.log(`QR Code scan error`, errorMessage)
				}
			)
		},
		//确定使用
		confirmFn() {
			this.$emit('photo-confirmed', this.imageUrl)
			console.log('this.imageUrl', this.imageUrl)
		},
	},
}
</script>

<style lang="less" scoped>
.mainContainer {
	margin: 0 auto;
	width: 500px;
	display: flex;
	flex-direction: column;
	justify-content: center;
	.up {
		width: 350px;
		height: 200px;
		border: 2px solid rgb(179, 175, 175);
		border-radius: 10px;
	}
	.down {
		margin-top: 10px;
	}
}
</style>
